#pragma once
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include "Comm.hpp"
#include <string>
#include <cstring>
#include <memory>
#include "Log.hpp"
#include <errno.h>
#include <cstring>
#define CONV(sock_ptr) ((struct sockaddr *)(sock_ptr))
static const int DEFAULT_BACKLOG = 5;
static const int DEFAULT_SOCKFD = -1;
class Socket
{
public:
    Socket() {}
    virtual ~Socket() {}; // 析构的虚函数？？        //TODO
    virtual void CreateSocket() = 0;
    virtual void BindSocket(uint16_t port) = 0;
    virtual bool SetListenSocket(int backlog = DEFAULT_BACKLOG) = 0;
    virtual Socket *AcceptConnection(std::string &peerip, uint16_t &peerport) = 0;
    virtual bool ConnectServer(const std::string &peerip, uint16_t peerport) = 0;
    virtual void CloseSockfd() = 0;
    virtual int GetSockfd() = 0;
    virtual std::string Recv() = 0;
    virtual bool Send(const std::string &) = 0;

public:
    bool CreateListenSocket(uint16_t port, int backlog = DEFAULT_BACKLOG)
    {
        CreateSocket();
        BindSocket(port);
        return SetListenSocket(backlog);
    }
    bool CreateConnectSocket(const std::string &serverip, uint16_t serverport)
    {
        CreateSocket();
        return ConnectServer(serverip, serverport);
    }
    void CreateNormalSocket()
    {
    }
};

class TcpSocket : public Socket
{
public:
    TcpSocket(int sock = DEFAULT_SOCKFD)
        : _sockfd(sock)
    {
    }

    ~TcpSocket() // 析构的虚函数？？        //TODO
    {
        CloseSockfd();
    }
    void CreateSocket() override
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd == -1)
        {
            lg.LogMessage(Fatal, "create socket error, errno: %d: %s\n", errno, strerror(errno));
            exit(socket_err);
        }
        lg.LogMessage(Info, "create socket success\n");
    }
    void BindSocket(uint16_t port) override
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof server);
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = INADDR_ANY;
        server.sin_port = htons(port);

        int ok = bind(_sockfd, CONV(&server), sizeof server);
        if (ok == -1)
        {
            lg.LogMessage(Fatal, "bind socket error, errno: %d: %s\n", errno, strerror(errno));
            exit(bind_err);
        }
        lg.LogMessage(Info, "bind socket success\n");
    }
    bool SetListenSocket(int backlog = DEFAULT_BACKLOG) override // 协变
    {
        int sock = listen(_sockfd, backlog); // 迷糊了正确返回的是0，不是新的fd
        if (sock == -1)
        {
            lg.LogMessage(Fatal, "listen socket error, errno: %d: %s\n", errno, strerror(errno));
            return false;
        }
        lg.LogMessage(Info, "listen socket success\n");
        // std::cout << "SetListenSocket"<<sock <<_sockfd<< std::endl;
        return true;
    }
    TcpSocket *AcceptConnection(std::string &peerip, uint16_t &peerport) override
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof peer);
        socklen_t len = sizeof(peer);
        int sockfd = accept(_sockfd, CONV(&peer), &len);
        if (sockfd == -1)
            return nullptr;
        else
        {
            peerip = inet_ntoa(peer.sin_addr);
            peerport = ntohs(peer.sin_port);
            // std::cout << "AcceptConnection:"<< peerport << peer.sin_port<< std::endl;
            return new TcpSocket(sockfd);
        }
    }
    bool ConnectServer(const std::string &serverip, uint16_t serverport) override
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof server);
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(serverip.c_str());
        server.sin_port = htons(serverport);
        int ok = connect(_sockfd, CONV(&server), sizeof server);
        if (ok == -1)
            return false;
        else
            return true;
    }

    void CloseSockfd() override
    {
        if (_sockfd > DEFAULT_SOCKFD)
            close(_sockfd);
    }
    int GetSockfd() override
    {
        return _sockfd;
    }
    void SetSockfd(int sockfd)
    {
        _sockfd = sockfd;
    }
    std::string Recv() override
    {
        char buffer[1024];
        int n = recv(_sockfd, buffer, sizeof buffer - 1, 0);
        // for (int i = 0; i < n; i++)
        //     std::cout << "buffer" << i << ": " << buffer[i] << std::endl; //接收的是没问题的
        if (n > 0)
        {
            buffer[n] = 0;   //发现问题了
            return buffer;
        }
        else
            return std::string();
    }
    bool Send(const std::string &package) override
    {
        int ok = send(_sockfd, package.c_str(), package.size(), 0);
        if (ok == -1)
            return false;
        else
            return true;
    }

private:
    int _sockfd;
};